package cn.touna.jss.modules.third.pacra;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.PacraProperties;
import cn.touna.jss.common.util.HttpUtil;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.pacra.entity.PacraRequestEntity;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.*;

import java.security.KeyStore;

import java.util.HashMap;
import java.util.Map;

/**
 * 凭安征信
 * Created by Administrator on 2017/7/13.
 */
@RestController
public class PacraService {

    @Resource(name = "httpsRestTemplate")
    private RestTemplate restTemplate = null;

    @Autowired
    private PacraProperties configProperties;

    private static final Logger logger = LogManager.getLogger(PacraService.class);

    private String keyPwd = "123456";
    private KeyStore keyStore;

    private synchronized KeyStore getKeyStore() {
        if (keyStore == null) {
            try {
                String keyName;
//                keyName = "CA.jks";
                keyName = "CACerts.jks";
                InputStream inputStream = getClass().getClassLoader().getResourceAsStream(keyName);
                keyStore = HttpUtil.getKeyStore(inputStream, keyPwd);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.getMessage(), e);
            }
        }
        return keyStore;
    }

    @ApiMapping(value="pacra.grayscaleStat",desc="凭安.染黑值")
    public Response grayscaleStat(PacraRequestEntity request) {
        Response validResponse = ValidUtil.valid(request);
        if (validResponse != null)
            return validResponse;

        Map<String, String> map = new HashMap<>();
        map.put("phone", request.getMobile());
        map.put("name", request.getName());
        map.put("idcard", request.getIdCard());
        map.put("imei", request.getImei());
        map.put("imsi", request.getImei());
        map.put("vkey", configProperties.getVkey());
        map.put("apply_date", request.getApplyDate());
        map.put("file_charset", request.getFileCharset());
        map.put("version", "v2");
        map.put("call_details", request.getCallDetails());

        try {
            KeyStore keyStore = getKeyStore();
            String content = HttpUtil.map2Url(map);
            String res = HttpUtil.post(configProperties.getGrayscaleStatUrl(), content, HttpUtil.CONTENT_TYPE_FORM, keyStore, keyPwd);
//            String res = HttpUtil.postForm(configProperties.getGrayscaleStatUrl(), map);
            JSONObject jRes = JSONObject.parseObject(res);
            if (jRes.getInteger("result") == 200) {
                return ResponseFactory.success(res);
            }
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, jRes.getString("message"));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    @ApiMapping(value="pacra.grayscaleStatReport",desc="凭安.grayscaleStatReport")
    public Response grayscaleStatReport(PacraRequestEntity request) {
        Response validResponse = ValidUtil.valid(request);
        if (validResponse != null)
            return validResponse;
        long startTime = System.currentTimeMillis();

        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
        map.add("phone", request.getMobile());
        map.add("name", request.getName());
        map.add("idcard", request.getIdCard());
        map.add("imei", request.getImei());
        map.add("imsi", request.getImei());
        map.add("vkey", configProperties.getVkey());
        map.add("apply_date", request.getApplyDate());
        map.add("file_charset", request.getFileCharset());

        ByteArrayResource byteArrayResource = new ByteArrayResource(request.getCallDetails().getBytes()) {
            @Override
            public String getFilename() throws IllegalStateException {
                return "c://callDetails.json";
            }
        };
        map.add("call_details", byteArrayResource);

        try {
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map);
            ResponseEntity<byte[]> response = restTemplate.exchange(configProperties.getGrayscaleStatReportUrl(), HttpMethod.POST, httpEntity, byte[].class);
            byte[] bytes = response.getBody();
            boolean success = true;
            String responseStr = "failed";
            if (bytes != null && bytes.length > 1) {
                String testStr = new String(bytes, 0, 1);
                if ("{".equals(testStr)) {
                    responseStr = new String(bytes);
                    success = false;
                }
            }
            long endTime = System.currentTimeMillis();
            logger.info("【Pacra】--返回数据SUCESS,接口调用耗时:startTime={},responstr={}", endTime - startTime, responseStr);

            if (success) {
                return ResponseFactory.success(bytes);
            } else {
                return new Response().fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
            }
        } catch (Exception e) {
            return new Response().fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR);
        }
    }
}
